package com.ycz.sas.jgen.handler;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.ycz.sas.jgen.domain.CacheInfo;

public class ConfigDataHandler {

	private CacheInfo data;

	public ConfigDataHandler(){
		reset();
	}

	public void reset(){
		data = new CacheInfo();
	}

	public CacheInfo getCache(){
		return data;
	}

	public void loadConfigData(String fileName){
		FileChannel channel = data.getFileLocks().get(fileName).channel();

		String[] lines = null;
		try {
			ByteBuffer buffer = ByteBuffer.allocate((int)channel.size());
			channel.read(buffer);
			String fileData = new String(buffer.array(), "GBK");
			lines = fileData.split("\\n");
		} catch (IOException e) {
			e.printStackTrace();
		}

		for(String line : lines){
			if(!line.contains("="))
				data.getPaths().add(line);
			else{
				String[] linedata = line.split("=");
				if(linedata.length == 2){
					if(line.startsWith("SourcePath"))
						data.setSourcePath(line.split("=")[1]);
					if(line.startsWith("BasePath"))
						data.setComparePath(line.split("=")[1]);
					if(line.startsWith("CustomPath"))
						data.setCustomPath(line.split("=")[1]);
					if(line.startsWith("UpdatePath"))
						data.setTargetPath(line.split("=")[1]);
					if(line.startsWith("JarFile"))
						data.setJarPath(line.split("=")[1]);
					if(line.startsWith("IgnoreFolders"))
						data.setIgnoreFolders((line.split("=")[1]));
				}
			}
		}

//		BufferedReader in = null;
//		try{
//			String cfgFile = data.getConfigPath();
//			in = new BufferedReader(new InputStreamReader(new FileInputStream(cfgFile)));
//
//			String line = null;
//			while ((line = in.readLine()) != null) {
//				if(!line.contains("="))
//					data.getPaths().add(line);
//				else{
//					String[] linedata = line.split("=");
//					if(linedata.length == 2){
//						if(line.startsWith("SourcePath"))
//							data.setSourcePath(line.split("=")[1]);
//						if(line.startsWith("BasePath"))
//							data.setComparePath(line.split("=")[1]);
//						if(line.startsWith("CustomPath"))
//							data.setCustomPath(line.split("=")[1]);
//						if(line.startsWith("UpdatePath"))
//							data.setTargetPath(line.split("=")[1]);
//						if(line.startsWith("JarFile"))
//							data.setJarPath(line.split("=")[1]);
//						if(line.startsWith("IgnoreFolders"))
//							data.setIgnoreFolders((line.split("=")[1]));
//					}
//				}
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally{
//			if (in != null) {
//				try {
//					in.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
	}

	public void saveConfig(String fileName){
		FileChannel channel = data.getFileLocks().get(fileName).channel();

		ByteBuffer buffer = ByteBuffer.allocate(data.bytesize() + 2);

		String line = null;
		if(data.getSourcePath() != null){
			line = "SourcePath="+data.getSourcePath()+"\n";
			buffer.put(line.getBytes());
		}
		if(data.getComparePath() != null){
			line = "BasePath="+data.getComparePath()+"\n";
			buffer.put(line.getBytes());
		}
		if(data.getCustomPath() != null){
			line = "CustomPath="+data.getCustomPath()+"\n";
			buffer.put(line.getBytes());
		}
		if(data.getTargetPath() != null){
			line = "UpdatePath="+data.getTargetPath()+"\n";
			buffer.put(line.getBytes());
		}
		if(data.getJarPath() != null){
			line = "JarFile="+data.getJarPath()+"\n";
			buffer.put(line.getBytes());
		}
		if(data.getIgnoreFolders() != null){
			line = "IgnoreFolders="+data.getIgnoreFolders()+"\n";
			buffer.put(line.getBytes());
		}

		List<String> pathList = data.getPaths();
		for (int i = 0, len = pathList.size(); i < len; i++) {
			line = pathList.get(i) + "\n";
			buffer.put(line.getBytes());
		}
		try {
			FileOprate.emptyFile(data.getConfigPath());
			buffer.rewind();
			channel.position(0);
			System.out.println(channel.write(buffer));
			System.out.println(channel.size());
		} catch (IOException e) {
			e.printStackTrace();
		}
//		BufferedWriter out = null;
//		try {
//			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(cfgFile)));
//			if(data.getSourcePath() != null)
//				out.write("SourcePath="+data.getSourcePath()+"\n");
//			if(data.getComparePath() != null)
//				out.write("BasePath="+data.getComparePath()+"\n");
//			if(data.getCustomPath() != null)
//				out.write("CustomPath="+data.getCustomPath()+"\n");
//			if(data.getTargetPath() != null)
//				out.write("UpdatePath="+data.getTargetPath()+"\n");
//			if(data.getJarPath() != null)
//				out.write("JarFile="+data.getJarPath()+"\n");
//			if(data.getIgnoreFolders() != null)
//				out.write("IgnoreFolders="+data.getIgnoreFolders()+"\n");
//			List<String> pathList = data.getPaths();
//			for (int i = 0, len = pathList.size(); i < len; i++) {
//				out.write(pathList.get(i)+ "\n");
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally{
//			if (out != null) {
//				try {
//					out.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
	}

	public String analyse(){
		StringBuffer resultbuffer = new StringBuffer();
		ScanNew scan = new ScanNew();

		scan.setCOMPAREPATH(data.getComparePath());
		scan.setSOURCEPATH(data.getSourcePath());
		scan.setTARGETPATH(data.getTargetPath());
		scan.setIgnoreUpdate(false);
		try {
			scan.setFilter(data.getPaths());
			scan.loadNegaFilter(data.getIgnoreFolders());
			List<File> filelist = scan.loadFilename(new File(scan.getSOURCEPATH()));
			data.setDiffFiles(filelist);
			if(filelist.size() == 0)
				resultbuffer.append("对比结果: 当前所选路径中无更新文件");
			else{
				resultbuffer.append("对比结果: 当前所选路径中存在 ").append(filelist.size()).append("  个更新文件\n");
				for(File file :filelist){
					resultbuffer.append(file.getAbsolutePath()).append("\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultbuffer.toString();
	}

	public String generateJar() throws Exception{
		ScanNew scan = new ScanNew();
		scan.setCfgPath(data.getConfigPath());
		scan.setCOMPAREPATH(data.getComparePath());
		scan.setSOURCEPATH(data.getSourcePath());
		scan.setTARGETPATH(data.getTargetPath());
		scan.setIgnoreUpdate(true);
		scan.setFilter(data.getPaths());
		scan.loadNegaFilter(data.getIgnoreFolders());
		FileOprate fileop = new FileOprate();
		fileop.delAllFile(data.getTargetPath());
		scan.analysis();
		JarOprate jarOprate = new JarOprate();
		jarOprate.jar(data.getTargetPath(), data.getJarPath());
		return data.getJarPath();
	}

	public boolean checkPathExist(String path){
		List<String> pathList = data.getPaths();
		int len = pathList.size();
		for (int i = 0; i < len; i++) {
			if(pathList.get(i).equals(path))
				return true;
		}
		return false;
	}

	public void lockCfgFile(String fileName){
		FileLock fl;
		try {
			fl = FileOprate.lockFile(fileName, "rw");
			data.getFileLocks().put(fileName, fl);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void releaseCfgFile(String fileName){
		if(data != null && data.getFileLocks() != null
				&& data.getFileLocks().containsKey(fileName)){
			FileLock fl = data.getFileLocks().get(fileName);
			try {
				fl.release();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					fl.channel().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void releaseAllCfgFile(){
		if(data != null && data.getFileLocks() != null){
			Map<String, FileLock> map = data.getFileLocks();
			for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
				Map.Entry<String, FileLock> entry = (Map.Entry<String, FileLock>) iterator.next();

				releaseCfgFile(entry.getKey());
			}
		}
	}

}
